package com.atguigu.yygh.order.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.atguigu.yygh.common.handler.YyghException;
import com.atguigu.yygh.common.service.MqConst;
import com.atguigu.yygh.common.service.RabbitService;
import com.atguigu.yygh.enums.OrderStatusEnum;
import com.atguigu.yygh.hosp.client.HospitalFeignClient;
import com.atguigu.yygh.model.order.OrderInfo;
import com.atguigu.yygh.model.user.Patient;
import com.atguigu.yygh.order.mapper.OrderInfoMapper;
import com.atguigu.yygh.order.service.OrderService;
import com.atguigu.yygh.order.service.WeixinService;
import com.atguigu.yygh.order.utils.HttpRequestHelper;
import com.atguigu.yygh.user.client.PatientFeignClient;
import com.atguigu.yygh.vo.hosp.ScheduleOrderVo;
import com.atguigu.yygh.vo.msm.MsmVo;
import com.atguigu.yygh.vo.order.OrderCountQueryVo;
import com.atguigu.yygh.vo.order.OrderCountVo;
import com.atguigu.yygh.vo.order.OrderMqVo;
import com.atguigu.yygh.vo.order.OrderQueryVo;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import feign.Param;
import org.joda.time.DateTime;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Random;
import java.util.stream.Collectors;

@Service
public class OrderServiceImpl extends ServiceImpl<OrderInfoMapper, OrderInfo> implements OrderService {
    @Autowired
    private PatientFeignClient patientFeignClient;
    @Autowired
    private HospitalFeignClient hospitalFeignClient;
    @Autowired
    private RabbitService rabbitService;
    @Autowired
    private WeixinService weixinService;

    /**
     * 创建订单
     *
     * @param scheduleId 排班id
     * @param patientId  就诊人id
     * @return
     */
    @Override
    public Long saveOrder(String scheduleId, Long patientId) {
        //1、根据patientId跨模块 （user），获取就诊人相关数据
        Patient patient = patientFeignClient.getPatient(patientId);
        if (patient == null) {
            throw new YyghException(20001, "获取就诊人相关数据失败");
        }
        //2、根据scheduleId跨模块（hosp），获取排班相关数据
        ScheduleOrderVo scheduleOrderVo = hospitalFeignClient.getScheduleOrderVo(scheduleId);
        if (scheduleOrderVo == null) {
            throw new YyghException(20001, "获取排班相关数据失败");
        }
        //3、判断是否可以挂号
        //     和当前系统时间比较（起始时间）， 当前时间不可以预约
        if (new DateTime(scheduleOrderVo.getStartTime()).isAfterNow() ||
                new DateTime(scheduleOrderVo.getEndTime()).isBeforeNow()) {
            throw new YyghException(20001, "未在挂号时间内");
        }
        //  剩余可预约数
        if (scheduleOrderVo.getAvailableNumber() < 1) {
            throw new YyghException(20001, "号已挂满");
        }
        //4、根据数据创建挂号订单，并入库
        OrderInfo orderInfo = new OrderInfo();
        BeanUtils.copyProperties(scheduleOrderVo, orderInfo);
        String outTradeNo = System.currentTimeMillis() + "" + new Random().nextInt(100);
        orderInfo.setOutTradeNo(outTradeNo);
        orderInfo.setUserId(patient.getUserId());
        orderInfo.setPatientId(patientId);
        orderInfo.setPatientName(patient.getName());
        orderInfo.setPatientPhone(patient.getPhone());
        orderInfo.setOrderStatus(OrderStatusEnum.UNPAID.getStatus());
        this.save(orderInfo);

        //5、调用一样接口，进行挂号确认，成功后，更新订单
        Map<String, Object> paramMap = new HashMap<>();
        paramMap.put("hoscode", orderInfo.getHoscode());//医院编码
        paramMap.put("depcode", orderInfo.getDepcode());//科室编码
        paramMap.put("hosScheduleId", orderInfo.getHosScheduleId());//主键id
        paramMap.put("reserveDate", new DateTime(orderInfo.getReserveDate()).toString("yyyy-MM-dd"));//安排日期
        paramMap.put("reserveTime", orderInfo.getReserveTime());//预约安排时间
        paramMap.put("amount", orderInfo.getAmount());//医事服务费
        paramMap.put("name", patient.getName());//就诊人姓名
        paramMap.put("certificatesType", patient.getCertificatesType());  //证件类型
        paramMap.put("certificatesNo", patient.getCertificatesNo());  //证件编号
        paramMap.put("sex", patient.getSex()); //性别
        paramMap.put("birthdate", patient.getBirthdate()); //生日
        paramMap.put("phone", patient.getPhone()); //电话号
        paramMap.put("isMarry", patient.getIsMarry()); //婚否
        paramMap.put("provinceCode", patient.getProvinceCode()); //省
        paramMap.put("cityCode", patient.getCityCode()); //市
        paramMap.put("districtCode", patient.getDistrictCode());  //区
        paramMap.put("address", patient.getAddress());//地址
        //联系人
        paramMap.put("contactsName", patient.getContactsName());
        paramMap.put("contactsCertificatesType", patient.getContactsCertificatesType());
        paramMap.put("contactsCertificatesNo", patient.getContactsCertificatesNo());
        paramMap.put("contactsPhone", patient.getContactsPhone());
        paramMap.put("timestamp", HttpRequestHelper.getTimestamp());
        //String sign = HttpRequestHelper.getSign(paramMap, signInfoVo.getSignKey());
        paramMap.put("sign", "");
        JSONObject result = HttpRequestHelper.sendRequest(paramMap, "http://localhost:9998/order/submitOrder");

        //6、成功后更新订单
        if (result.getInteger("code") == 200) {
            JSONObject jsonObject = result.getJSONObject("data");
            //预约记录唯一标识（医院预约记录主键）
            String hosRecordId = jsonObject.getString("hosRecordId");
            //预约序号
            Integer number = jsonObject.getInteger("number");
            ;
            //取号时间
            String fetchTime = jsonObject.getString("fetchTime");
            ;
            //取号地址
            String fetchAddress = jsonObject.getString("fetchAddress");
            ;
            //更新订单
            orderInfo.setHosRecordId(hosRecordId);
            orderInfo.setNumber(number);
            orderInfo.setFetchTime(fetchTime);
            orderInfo.setFetchAddress(fetchAddress);
            baseMapper.updateById(orderInfo);
            //排班可预约数
            Integer reservedNumber = jsonObject.getInteger("reservedNumber");
            //排班剩余预约数
            Integer availableNumber = jsonObject.getInteger("availableNumber");

            //7、成功后，发送MQ消息，更新号源，发送短信通知
            //  7.1、封装订单相关信息对象
            OrderMqVo orderMqVo = new OrderMqVo();
            orderMqVo.setHoscode(orderInfo.getHoscode());
            orderMqVo.setHosScheduleId(orderInfo.getHosScheduleId());
            orderMqVo.setReservedNumber(reservedNumber);
            orderMqVo.setAvailableNumber(availableNumber);

            //  7.2、封装短信相关消息对象，存入订单相关信息对象
            //短信提示
            MsmVo msmVo = new MsmVo();
            msmVo.setPhone(orderInfo.getPatientPhone());
            String reserveDate =
                    new DateTime(orderInfo.getReserveDate()).toString("yyyy-MM-dd")
                            + (orderInfo.getReserveTime() == 0 ? "上午" : "下午");
            Map<String, Object> param = new HashMap<String, Object>() {{
                put("title", orderInfo.getHosname() + "|" + orderInfo.getDepname() + "|" + orderInfo.getTitle());
                put("amount", orderInfo.getAmount());
                put("reserveDate", reserveDate);
                put("name", orderInfo.getPatientName());
                put("quitTime", new DateTime(orderInfo.getQuitTime()).toString("yyyy-MM-dd HH:mm"));
            }};
            msmVo.setParam(param);
            orderMqVo.setMsmVo(msmVo);
            //  7.3、发送消息
            rabbitService.sendMessage(
                    MqConst.EXCHANGE_DIRECT_ORDER,
                    MqConst.ROUTING_ORDER,
                    orderMqVo
            );
        }
        //下单失败
        else {
            throw new YyghException(20001, "生成订单失败");
        }
        //返回订单号
        return orderInfo.getId();
    }

    /**
     * 带条件带分页查询订单列表
     *
     * @param pageParam
     * @param orderQueryVo
     * @return
     */
    @Override
    public IPage<OrderInfo> selectPage(Page<OrderInfo> pageParam, OrderQueryVo orderQueryVo) {
        //1、取出查询参数
        //orderQueryVo获取条件值
        Long userId = orderQueryVo.getUserId();
        String name = orderQueryVo.getKeyword(); //医院名称
        Long patientId = orderQueryVo.getPatientId(); //就诊人名称
        String orderStatus = orderQueryVo.getOrderStatus(); //订单状态
        String reserveDate = orderQueryVo.getReserveDate();//安排时间
        String createTimeBegin = orderQueryVo.getCreateTimeBegin();
        String createTimeEnd = orderQueryVo.getCreateTimeEnd();
        //2、验空，拼写查询条件
        //对条件值进行非空判断
        QueryWrapper<OrderInfo> wrapper = new QueryWrapper<>();
        if (!StringUtils.isEmpty(userId)) {
            wrapper.eq("user_id", userId);
        }
        if (!StringUtils.isEmpty(name)) {
            wrapper.like("hosname", name);
        }
        if (!StringUtils.isEmpty(patientId)) {
            wrapper.eq("patient_id", patientId);
        }
        if (!StringUtils.isEmpty(orderStatus)) {
            wrapper.eq("order_status", orderStatus);
        }
        if (!StringUtils.isEmpty(reserveDate)) {
            wrapper.ge("reserve_date", reserveDate);
        }
        if (!StringUtils.isEmpty(createTimeBegin)) {
            wrapper.ge("create_time", createTimeBegin);
        }
        if (!StringUtils.isEmpty(createTimeEnd)) {
            wrapper.le("create_time", createTimeEnd);
        }
        //3、带条件带分页查询
        //调用mapper的方法
        IPage<OrderInfo> pageModel = baseMapper.selectPage(pageParam, wrapper);
        //4、遍历集合翻译字段
        //编号变成对应值封装
        pageModel.getRecords().stream().forEach(item -> {
            this.packOrderInfo(item);
        });

        return pageModel;
    }

    /**
     * 根据订单id查询订单详情
     *
     * @param orderId 订单id
     * @return
     */
    @Override
    public OrderInfo getOrderInfo(Long orderId) {
        OrderInfo orderInfo = this.packOrderInfo(baseMapper.selectById(orderId));
        return orderInfo;
    }

    /**
     * 取消预约
     *
     * @param orderId 订单id
     * @return 成功 失败
     */
    @Override
    public Boolean cancelOrder(Long orderId) {
        //1、根据orderId查询订单信息
        OrderInfo orderInfo = baseMapper.selectById(orderId);
        if (orderInfo == null)
            throw new YyghException(20001, "订单信息有误");
        //2、校验是否已过取消预约截止时间（当前时间大于退号时间）
        DateTime dateTime = new DateTime(orderInfo.getQuitTime());
//        if (dateTime.isBeforeNow())
//            throw new YyghException(20001, "取消预约截止时间超时");
        //3、调用医院系统 取消预约
        //3.1、封装调用接口参数
        Map<String, Object> reqMap = new HashMap<>();
        reqMap.put("hoscode", orderInfo.getHoscode());   //医院编码
        reqMap.put("hosRecordId", orderInfo.getHosRecordId());   //医院方订单id
        reqMap.put("timestamp", HttpRequestHelper.getTimestamp());  //时间戳
        reqMap.put("sign", "");   //签名（省略）
        //3.2、借助工具发送请求获得响应
        JSONObject result = HttpRequestHelper.sendRequest(reqMap, "http://localhost:9998/order/updateCancelStatus");
        //3.3、判断取消结果
        if (result.getInteger("code") != 200) {
            throw new YyghException(20001, "取消预约失败");
        } else {
            //4、医院饭会取消成功，判断是否已支付
            //是否支付
            if (orderInfo.getOrderStatus().intValue()
                    ==
                    OrderStatusEnum.PAID.getStatus().intValue()//已支付
            ) {
                //5、已支付，进行微信退款
                Boolean aBoolean = weixinService.refund(orderId); //退款
                //5.1、判断是否已退款
                if (!aBoolean) {
                    throw new YyghException(20001, "微信退款失败");
                }
            }
            //6、更改订单状态
            orderInfo.setOrderStatus(OrderStatusEnum.CANCLE.getStatus());
            this.updateById(orderInfo);
            //7、发送MQ消息，更新号源信息，通知就诊人
            OrderMqVo orderMqVo = new OrderMqVo();
            orderMqVo.setHoscode(orderInfo.getHoscode());
            orderMqVo.setHosScheduleId(orderInfo.getHosScheduleId());
            //7.1、短信提示
            MsmVo msmVo = new MsmVo();
            msmVo.setPhone(orderInfo.getPatientPhone());
            orderMqVo.setMsmVo(msmVo);
            rabbitService.sendMessage(
                    MqConst.EXCHANGE_DIRECT_ORDER,  //交换机
                    MqConst.ROUTING_ORDER,          //路由
                    orderMqVo                       //
                                        );
        }
        return true;
    }

    /**
     * 就医提醒
     */
    @Override
    public void patientTips() {
        //1、根据系统日期查询当天就诊订单集合
        QueryWrapper<OrderInfo> wrapper = new QueryWrapper<>();
        wrapper.eq("reserve_date",new DateTime().toString("yyyy-MM-dd"));
        List<OrderInfo> orderInfoList = baseMapper.selectList(wrapper);
        //2、遍历集合，获取参数存入MsmVo
        orderInfoList.forEach(item->{
            MsmVo msmVo = new MsmVo();
            msmVo.setPhone(item.getPatientPhone());
            Map<String, Object> param = new HashMap<>();
            param.put("title", item.getHosname()+"|"+item.getDepname()+"|"+item.getTitle());
            param.put("reserveDate", item.getReserveDate());
            param.put("name", item.getPatientName());
            msmVo.setParam(param);
            //3、发送mq消息，实现短信提醒
            rabbitService.sendMessage(MqConst.EXCHANGE_DIRECT_MSM, MqConst.ROUTING_MSM_ITEM, msmVo);
        });
    }

    /**
     * 订单统计
     * @param orderCountQueryVo
     * @return
     */
    @Override
    public Map<String, Object> getCountMap(OrderCountQueryVo orderCountQueryVo) {
        //1、根据条件查询统计结果
        List<OrderCountVo> orderCountVoList
                = baseMapper.selectOrderCount(orderCountQueryVo);
        //2、根据orderCountVoList集合取出x，y轴数据
        //日期列表
        List<String> dateList
                =orderCountVoList.stream().map(OrderCountVo::getReserveDate).collect(Collectors.toList());
        //统计列表
        List<Integer> countList
                =orderCountVoList.stream().map(OrderCountVo::getCount).collect(Collectors.toList());
        //3、封装数据
        Map<String, Object> map = new HashMap<>();
        map.put("dateList", dateList);
        map.put("countList", countList);
        //4、返回
        return map;
    }

    //翻译
    private OrderInfo packOrderInfo(OrderInfo orderInfo) {
        orderInfo.getParam().put("orderStatusString", OrderStatusEnum.getStatusNameByStatus(orderInfo.getOrderStatus()));
        return orderInfo;
    }
}